package com.oss.service.impl;

import java.net.URL;
import java.text.ParseException;
import java.util.Date;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.utils.DateUtil;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.oss.base.baseconst.ConfigConst;

public class OssSignUrlService {
	
	
	public URL getSingUrl(){
		 OSSClient client = new OSSClient(ConfigConst.ENDPOINT, ConfigConst.ACCESSKEYID, ConfigConst.ACCESSKEYSECRET);

		// 失效时间
		Date expiration = new Date(new Date().getTime() + 3600 * 1000);

		// URL
		URL url = client.generatePresignedUrl(ConfigConst.BUCKETNAME, ConfigConst.KEY+"oss-java-sdk-21220.txt", expiration);
		
		
		return url;
	}
	
	public URL getPutSignUrl(String fileName){
		if(fileName == null){
			fileName = "oss-java-sdk-33187.txt";
		}
		
		OSSClient client = new OSSClient(ConfigConst.ENDPOINT, ConfigConst.ACCESSKEYID, ConfigConst.ACCESSKEYSECRET);
		Date expiration = new Date();
		try {
			expiration = DateUtil.parseRfc822Date("Wed, 18 Mar 2016 14:20:00 GMT");
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(ConfigConst.BUCKETNAME, ConfigConst.KEY+fileName, HttpMethod.PUT);
		//设置过期时间
		request.setExpiration(expiration);
		//设置Content-Type
		request.setContentType("application/octet-stream");
		// 添加user meta
		request.addUserMetadata("author", "aliy");
		// 生成URL签名(HTTP PUT请求)
		URL signedUrl = client.generatePresignedUrl(request);
		System.out.println("signed url for putObject: " + signedUrl);
		return signedUrl;
	}
	
}
